package com.squirrel.common.util;

import com.squirrel.common.vo.CommentaryVO;
import org.apache.commons.codec.binary.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class BiliBiliDanmuUtils {


    /**
     * add @param commentary
     * modify by guan yuanjian
     * @date 2021/11/20 22:09
     */
    public static List<List> extractFromXML(Integer oid, List<CommentaryVO> commentary) {
        List<List> commentaryVOList = new ArrayList<>();
        try {
            String XmlStr = HttpRequest.getRawHtml(oid);
            SAXReader reader = new SAXReader();
            Document xmlDoc = reader.read(new ByteArrayInputStream(XmlStr.getBytes(StandardCharsets.UTF_8)));
            //获取弹幕XML根节点
            Element root = xmlDoc.getRootElement();
            //获取弹幕XML的所有d节点
            Iterator tickets = root.elementIterator("d");
            Element ticket = null;
            while (tickets.hasNext()) {
                ticket = (Element) tickets.next();
                //对d节点的属性进行提取存入实体类
                String dAttr = ticket.attribute("p").getValue();
                String[] attrArray = dAttr.split(",");
                //弹幕位置类型
                int type = 0;
                if (StringUtils.equals(attrArray[1], "4")) {
                    type = 2;
                } else if (StringUtils.equals(attrArray[1], "5")) {
                    type = 1;
                }
//                CommentaryVO commentaryVO = new CommentaryVO().setType(type).setAuthor(Long.parseLong(attrArray[7])).setTime(Integer.parseInt(attrArray[4])).setText(ticket.getText()).setColor(attrArray[6]);
                List<Object> itemList = new ArrayList();
                itemList.add(Double.parseDouble(attrArray[0]));//弹幕视频出现的时间
                itemList.add(type);//位置
                itemList.add(Integer.parseInt(attrArray[3]));//十进制颜色
                itemList.add(Long.parseLong(attrArray[7]));//发送弹幕的人的id
                itemList.add(ticket.getText());//弹幕内容
                commentaryVOList.add(itemList);

            }
        } catch (URISyntaxException | IOException | DocumentException e) {
            System.out.println("=================这不是B站的视频=======================");
            e.printStackTrace();
        }

        // 没有指定泛型，不管什么类型的数据都可以添加，不推荐
        for (CommentaryVO vo: commentary) {
            ArrayList list = new ArrayList();
            list.add(vo.getTime());
            list.add(vo.getType());
            list.add(vo.getColor());
            list.add(vo.getRealTime());
            list.add(vo.getText());

            commentaryVOList.add(list);
        }

        return commentaryVOList;
    }


}
